//
//  WeightHelper.swift
//  ScanBleBtDeviceMac
//
//  Created by Caijinglong on 2017/10/19.
//  Copyright © 2017年 ScanBleBtDeviceMac. All rights reserved.
//

import CoreBluetooth
import Foundation

class WeightHelper:NSObject,CBCentralManagerDelegate{

    var service = "FFE0"
    var character = "FFE1"
    
    static let shared = WeightHelper()
    
    lazy var cm:CBCentralManager = {
        return CBCentralManager(delegate: self, queue: nil)
    }()
    
    private override init(){
        super.init()
    }
    
    var isInit = false
    
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        //这里根据ios mac 会有所不同
        if #available(OSX 10.13, *) {
            //        if #available(iOS 10.0, *) {
            isInit = central.state == CBManagerState.poweredOn
        } else {
            isInit = central.state.rawValue == CBCentralManagerState.poweredOn.rawValue
        }
    }
    
    var scanType = 1
    var scanName = ""
    
    func scanForName(name:String){
        scanType = 1
        scanName = name
        cm.scanForPeripherals(withServices: [CBUUID(string: service)], options: nil)
        runDelay(3) {
            self.cm.stopScan()
        }
    }
    
    func scanForList(delegate:BLEBlueToothScanResultDelegate){
        scanType = 2
        devicesResultList.removeAll()
        cm.scanForPeripherals(withServices: [CBUUID(string: service)], options: nil)
        runDelay(3) {
            self.cm.stopScan()
            delegate.scanResult(resultList:self.devicesResultList)
        }
    }
    
    func connectDevice(device:CBPeripheral){
        cm.connect(device, options: nil)
    }
    
    var device:CBPeripheral? = nil
    var devicesResultList = [CBPeripheral]()
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        device = peripheral
        if let name = device?.name{
            if scanType == 1 && name == scanName{
                NSLog("扫描到 \(name)")
                cm.connect(peripheral, options: nil)
            }
        }
        
        if !devicesResultList.contains(peripheral){
            devicesResultList.append(peripheral)
        }
    }
    
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        NSLog("连接 \(peripheral.name) 成功!")
        peripheral.delegate = self
        peripheral.discoverServices([CBUUID(string:service)])
    }
    
    var delgate:WeightResultDelegate? = nil
}

extension WeightHelper:CBPeripheralDelegate{
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        peripheral.services?.forEach({ (service) in
            peripheral.discoverCharacteristics([CBUUID(string:self.character)], for: service)
        })
    }
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        if let count = service.characteristics?.count{
            for i in 0...count-1{
                if let c = service.characteristics?[i]{
                    NSLog("c = \(c.uuid.uuidString)")
                    peripheral.setNotifyValue(true, for: c)
                }
            }
        }
    }
    
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        if let data = characteristic.value{
            let gbkEncodingInt = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(CFStringEncodings.GB_18030_2000.rawValue))
            if let str = NSString.init(data: data, encoding: gbkEncodingInt){
                let result = String(str).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
                NSLog("result = \(result)")
                self.delgate?.weightResult(weight: String(str).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))
            }
        }
    }

}

protocol BLEBlueToothScanResultDelegate{
    func scanResult(resultList:[CBPeripheral])
}

protocol WeightResultDelegate{
    
    func weightResult(weight:String)
    
}
